<?php
/**
* @file chat.php
* Copyright (c) Friends Group. All rights reserved.
* $Id$
*
*/

require_once(realpath(dirname(__FILE__)) . '/../config.php');
require_once(realpath(dirname(__FILE__)) . '/../includes/common/ServiceFactory.php');
require_once(realpath(dirname(__FILE__)) . '/../includes/common/Utilities.php');
require_once(realpath(dirname(__FILE__)) . '/../includes/common/Validator.php');

Session::start(0);

$commonService = ServiceFactory::get();
$config = ServiceFactory::get("SystemConfiguration");
$userService = ServiceFactory::get("UserService");
$messageService = ServiceFactory::get("MessageService");
$authService = ServiceFactory::get("AuthenticationService");

if(!$authService -> isAuthenticated())
    Response::error("Access denied.", 401);

$user = $authService -> getCurrentUser();

$action = $_REQUEST['action'];
$userId = $_POST['userId'];

if(empty($userId))
{
    Response::error("Tham số không hợp lệ.");
}

try
{
    $user = $userService -> findUserById($userId);
    $userService -> updateLastAccessTime($userId);
    $userService -> logoutInactiveUser();
}
catch(Exception $ex)
{
    Response::error($ex -> getMessage());
}

switch ($action) {
    case 'getBuddyGroup':
        try
        {
            $str = getBuddyGroup($userId);
            Response::success($userId, $str);
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        
        break;
    case 'getBuddyList':
        
        try
        {
            $str = getBuddyList($userId);
            Response::success($userId, $str);
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'deleteBuddy':
        try
        {
            $buddy = $userService -> findUserByName($_POST['buddyName']);
            $userService -> removeUserFriend($userId, $buddy -> getID());
            Response::success("Đã xóa thành công {$buddy -> getNickname()} khỏi danh sách friend của {$user -> getNickname()}", getBuddyList($userId));
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'deleteGroup':
        try
        {
            $group = $userService -> findUserGroupById($userId, $_POST['groupId']);
            $userService -> deleteUserGroup($userId, $group);
            Response::success("Đã xóa thành công group {$group -> getGroupName()}", getBuddyList($userId));
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'addBuddy':
        try
        {
            $buddy = $userService -> findUserByName($_POST['buddyName']);
            $group = $userService -> findUserGroupById($userId, $_POST['groupId']);
            $userService -> addUserFriend($userId, $buddy -> getID(), $group);
            Response::success("Đã thêm thành công {$buddy -> getNickname()} vào danh sách friend của {$user -> getNickname()}", getBuddyList($userId));
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'getBuddyInfo':
        try
        {
            $buddy = $userService -> findUserByName($_POST['buddyName']);
            Response::success("{$buddy -> getID()}");
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'addGroup':
        try
        {
            $groupName = $_POST['groupName'];
            if(!Validator::validateAlphaNum($groupName, false) || strlen($groupName) > 60)
                Response::error("Tên nhóm chỉ chứa chữ cái và số và tối đa 60 ký tự");
            
            $group = new UserGroup($userId, TextUtility::htmlEncode($groupName));
            $userService -> createUserGroup($userId, $group);
            Response::success("Đã thêm thành công group {$group -> getGroupName()}", getBuddyList($userId));
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'renameGroup':
        try
        {
            if(!Validator::validateAlphaNum($_POST['groupName'], false) || strlen($_POST['groupName']) > 60)
                Response::error("Tên nhóm chỉ chứa chữ cái và số và tối đa 60 ký tự");
            
            $group = $userService -> findUserGroupById($userId, $_POST['groupId']);
            $group -> setGroupname(TextUtility::htmlEncode($_POST['groupName']));
            $userService -> updateUserGroup($userId, $group);
            Response::success("Đổi tên thành công", getBuddyList($userId));
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'changeBuddyAlias':
        try
        {
            $newAlias = $_POST['alias'];
            if(!isset($newAlias) || empty($newAlias) || strlen($newAlias) > 60 || !Validator::validateAlphaNum($newAlias, false))
                Response::error("Tên chỉ chứa chữ cái và số và tối đa 60 ký tự");
            
            $buddy = $userService -> findUserByName($_POST['buddyName']);
            $userService -> changeBuddyAlias($userId, $buddy -> getID(), TextUtility::htmlEncode($newAlias));
            Response::success("Đổi tên thành công", getBuddyList($userId));
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'updateMyStatus':
        try
        {
            $newStatus = $_POST['status'];
            if(strlen($newStatus) > intval($config -> getSetting("status-length")))
                Response::error("Chiều dài tối đa của Status không được quá {$config -> getSetting("status-length")} ký tự");
            
            if($newStatus == "Offline")
            {
                $userService -> setUserOption($userId, "last-status", $userService -> getUserStatus($userId) -> getStatusText());
                $userService -> setUserStatus($userId, $commonService -> getStatusByName("Offline"));
                Response::success("Logout");
            }
            else
            {
                $newStatus = TextUtility::htmlEncode($newStatus);
                $status = $commonService -> getStatusByName($newStatus);
                $userService -> setUserStatus($userId, $status, $newStatus);
                Response::success("Update status thành công", getBuddyList($userId));
            }
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'sendMessage':
        try
        {
            $type = $_POST['mst'];
            if($type == "Warning")
            {
                if($authService -> isUser($user))
                {
                    throw new Exception("Bạn không có quyền gửi message thông báo");
                }
            }
            elseif($type == "Alert")
            {
                if($authService -> isUser($user))
                {
                    throw new Exception("Bạn không có quyền gửi message cảnh cáo");
                }
            }
            elseif($type != "Normal")
                throw new Exception("Loại message không hỗ trợ");
            
            $receiverId = $userService -> findUserByName($_POST['receiver']) -> getID();
            $message = $_POST['message'];
            $message = TextUtility::htmlEncode($message);
            $ms = new Message($message, $commonService -> getMessageTypeByName($type) -> getID());
            $messageService -> sendUserMessage($userId, $receiverId, $ms, $commonService -> getMessageTypeByName($type));
            $message = TextUtility::bbCodeFormat($message);
            if($config -> getSetting("use-emoticon") == "1")
                $message = $commonService -> replaceEmoticon($message, $userService -> getUserOption($userId, "emoticon-theme"));
            $message = base64_encode($message);
            Response::success($message);
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    case 'getAllMessages':
        try
        {
            $str = getAllMessages($userId);
            Response::success($userId, $str);
        }
        catch(Exception $ex)
        {
            Response::error($ex -> getMessage());
        }
        break;
    default:
        Response::error("Dịch vụ chưa sẵn sàng");
        break;
}

exit();


function getBuddyList($userId)
{
    global $userService;
    global $commonService;
    global $user;
    
    $str = '{"groups": [';
    $groups = $userService -> getUserGroups($userId);
    if(count($groups))
    {
        foreach($groups as $group)
        {
            $str = $str . '{"name":"'.$group -> getGroupName().'", "id": "group-'.$group -> getID().'", "items" :[';
            $friends = $userService -> getFriendsInGroup($userId, $group);
            if(count($friends))
            {
                foreach($friends as $friend)
                {
                    $fullname = $friend -> getFirstname() . " " . $friend -> getLastname();
                    $alias = $friend -> getProperty("buddyAliasName");
                    $status = base64_encode($userService -> getUserStatus($friend -> getID()) -> getStatusText());
                    $str = $str.'{"id": "buddy-'.$friend -> getNickname().'", "name": "'.$fullname.'", "alias":"'.$alias.'", "avatar": "'.$commonService -> getAvatarSrc($friend -> getAvatarID(), 2).'", "status": "'.$status.'"},';
                }
            }
            $str = $str.'{"id":""}]},';
        }
    }
    $str = $str . '{"id":""}]}';
    
    return $str;
}

function getBuddyGroup($userId)
{
    global $userService;
    $str = '{"groups": [';
    $groups = $userService -> getUserGroups($userId);
    if(count($groups))
    {
        foreach($groups as $group)
        {
            $str = $str . '{"name": "'.$group -> getGroupName().'", "id": "group-'.$group -> getID().'"},';
        }
    }
    $str = $str . '{"id": ""}]}';
    
    return $str;
}

function getAllMessages($userId)
{
    global $userService;
    global $messageService;
    global $commonService;
    global $config;
    
    $str = '{"messages": [';
    
    $message = $messageService -> getUserMessages($userId);
    if(count($message))
    {
        foreach ($message as $ms)
        {
            $sender = $userService -> findUserById($ms -> getProperty("senderID"));
            $senderName = $userService -> findUserById($ms -> getProperty("senderID")) -> getNickname();
            $time = DateUtility::friendlyDate($ms -> getPostTime(), "Y m d H:i:s");
            $type = "Buddy";
            
            if($commonService -> getMessageTypeByName("Warning") -> getID() == $ms -> getMessageTypeID())
            {
                $type = "Warning";
            }
            elseif($commonService -> getMessageTypeByName("Alert") -> getID() == $ms -> getMessageTypeID())
            {
                $type = "Alert";
            }
            
            $content = $ms -> getMessages();
            $content = TextUtility::bbCodeFormat($content);
            if($config -> getSetting("use-emoticon") == "1")
                $content = $commonService -> replaceEmoticon($content, $userService -> getUserOption($userId, "emoticon-theme"));
            $content = base64_encode($content);
            
            $status = base64_encode($userService -> getUserStatus($sender -> getID()) -> getStatusText());
            
            $infos = '"name": "'.$senderName.'", "alias": "'.$senderName.'", "status": "'.$status.'", "avatar": "'.$commonService -> getAvatarSrc($sender -> getAvatarID(), 2).'", "id": "'.$senderName.'"';
            
            $str = $str . '{"sender": "'.$senderName.'", "mst": "'.$type.'", "time": "'.$time.'", "ms" : "'.$content.'", "senderinfo": {'.$infos.'}},';
        }
    }
    
    $str = $str . '{"sender": ""}]}';
    return $str;
}

?>